import { onBeforeMount, onMounted, onUnmounted, ref } from "vue";
import { useAgvApi } from "../api/agv";
import getVisualization from "../api/Visualization";
import Base from "../baby/Base";
import initMap from "../map/init";
import getCvInfo from "../api/CvInfo";


const useData = () => {
  const dataRef = ref<null | any>(null);
  const dataCV = ref<null | any>(null);
  const timerIdRef = ref<number | null>(null);
  const base = Base.getInstance(true);

  const loadData = async () => {
    try {
      const res = await getVisualization();
      dataRef.value = res.data
      // console.log(res.data);

      const cvRes = await getCvInfo()
      dataCV.value = cvRes.data
      // console.log(cvRes.data);



      // -------------
      const statusRes = await useAgvApi().getAgvStatus({
        m_ip: '10.13.32.11'
      })
      const { status } = statusRes.data.data as TAgvStatus

      if (status) {

        const res = await useAgvApi().getAgvAll1Info({
          m_ip: '10.13.32.11'
        })

        const { x, y, angle, battery_level,
          vx, task_status, current_station,
          unfinished_path, charging, battery_cycle, battery_temp, today_odo, odo, time, total_time, controller_humi, controller_temp, controller_voltage,
          voltage,
          current,
          confidence,
          emergency,
          blocked,
          DI,
          DO,
          task_type,
          current_lock
        } = res.data.data as TAll1;


        // console.log(tasklist_status);

        // console.log(task_status);

        // 设置button的状态
        base.gui.setHeaderBtnStatus(task_status)

        // 高亮线路
        base.ground.changePathColor(task_status, current_station, unfinished_path)
        base.agvObjOne.moveAgv(x, y, angle)
        base.agvObjOne.changeLabel({
          battery: battery_level,
          speed: vx,
          status: status
        })


        // 更新机器人信息
        base.gui.changeInfoPanel({
          batteryCycle: battery_cycle,
          batteryTemp: battery_temp,
          todayOdo: today_odo,
          odo: odo,
          time: time,
          totalTime: total_time,
          controllerTemp: controller_temp,
          controllerHumi: controller_humi,
          controllerVoltage: controller_voltage,
          current: current,
          voltage: voltage,
          confidence: confidence,
          emergency: emergency,
          blocked: blocked,
          diStatus: DI,
          doStatus: DO,
          taskStatus: task_status,
          taskType: task_type,
          currentLock: current_lock
        })

      }

    } catch (err) {
      // console.warn(err);
    }
  };

  onBeforeMount(async () => {
  })

  onMounted(() => {
    loadData();
    timerIdRef.value = setInterval(async () => await loadData(), 3000);
  });


  onUnmounted(() => {
    clearInterval(timerIdRef.value!);
  });

  return {
    dataRef,
    dataCV,
    timerIdRef,
  }
}

export default useData
